

<template>
	<view class="app-reserve">
		<!-- 		<uni-calendar
		:insert="true"
		:lunar="false" 
		:start-date="'2019-3-2'"
		:end-date="'2029-5-20'"
		@change="changeCalendar"
		 /> -->
		<view class="app-wrapper">
			<text class="app-title">体检人信息</text>
			<view class="app-tip">
				<mp-html :content="rich" @linktap="linkTaps"></mp-html>
			</view>
			<!-- <up-calendar :show="true" @confirm="changeCalendar"></up-calendar> -->
			<uni-forms class="app-form" ref="formRef" v-model="formData">
				<view class="select-wrapper">
					<view class="select-left">
						<uni-forms-item name="name">
							<view class="form-item">
								<view class="form-label">
									<text>*</text>
									<text>体检人姓名：</text>
								</view>
								<view class="form-content">
									<input v-model="formData.name" placeholder="请输入姓名" :disabled="!isFormEditable" />
								</view>
							</view>
						</uni-forms-item>

						<uni-forms-item name="phone">
							<view class="form-item" style="border-bottom: none;">
								<view class="form-label">
									<text>*</text>
									<text>体检人手机：</text>
								</view>
								<view class="form-content">
									<input v-model="formData.phone" placeholder="请输入手机" :disabled="!isFormEditable" />
								</view>
							</view>
						</uni-forms-item>
					</view>

					<view class="select-right" :class="{ 'disabled': !isFormEditable }"
						@click="isFormEditable ? openCustomerPicker() : null">
						<image :src="imgUrl('/static/img/icons/male.png')" mode="aspectFill" />
						<text>选择体检人</text>
					</view>
				</view>

				<view class="app-tip">
					<text>手机号用于接收检前提醒，报告出具查询等信息</text>
				</view>

				<uni-forms-item name="license_type">
					<view class="form-item">
						<view class="form-label">
							<text>*</text>
							<text>证件类型：</text>
						</view>
						<view class="form-content">
							<radio-group @change="isFormEditable ? handleLicenseTypeChange : null">
								<label v-for="(item, index) in licenseType" :key="index">
									<radio :checked="formData.license_type === item.value" :value="item.value"
										:disabled="!isFormEditable" color="#FF7F36" />
									{{ item.label }}
								</label>
							</radio-group>
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item name="license_number">
					<view class="form-item">
						<view class="form-label">
							<text>*</text>
							<text>证件号码：</text>
						</view>
						<view class="form-content">
							<input v-model="formData.license_number" placeholder="请输入证件号码"
								:disabled="!isFormEditable" />
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item name="gender">
					<view class="form-item">
						<view class="form-label">
							<text>*</text>
							<text>体检人性别：</text>
						</view>
						<view class="form-content">
							<radio-group @change="isFormEditable ? handleGenderChange : null">
								<label v-for="(item, index) in genderType" :key="index">
									<radio :checked="formData.gender === item.value" :value="item.value"
										:disabled="!isFormEditable" color="#FF7F36" />
									{{ item.label }}
								</label>
							</radio-group>
						</view>
					</view>
				</uni-forms-item>

				<uni-forms-item name="ismarried" v-if="formData.gender==1">
					<view class="form-item">
						<view class="form-label">
							<text>*</text>
							<text>婚姻状态：</text>
						</view>
						<view class="form-content">
							<radio-group @change="changeMarried">
								<label v-for="(item, index) in marriedType" :key="index">
									<radio :checked="isMarried === item.value" :value="item.value" color="#FF7F36" />
									{{ item.label }}
								</label>
							</radio-group>
						</view>
					</view>
				</uni-forms-item>
				<!-- 女性提示 --> 
				<view class="tip-info" v-if="formData.gender==1"> 
					<text class="tip-title">女性体检注意事项</text>
					<view class="tip-content"> 
						<view class="tip-margin">1.<text style="color:#F56C6C">怀孕或可能已受孕者</text>,请先告知医护人员,勿做放射检查(含X射线、CT、钼靶等),慎做妇科内诊及阴超检查。</view>
						<view class="tip-margin">2.妇科检查或阴超检查仅<text style="color:#F56C6C">限于已婚或有性生活者</text>,检前建议排空膀胱。</view>
						<view class="tip-margin">3.做宫颈涂抹片检查者,受检前三日起,请勿做阴道冲洗,勿使用阴道药物,以得到准确的检查结果。</view>
						<view class="tip-margin"> 4.月经期间请勿留取尿液、粪便,暂缓阴超及妇科检查,待经期结束3-5天后再补检。</view>
					</view>
				</view> 
		<!-- <uni-forms-item name="address_area" >
					<view class="form-item">
						<view class="form-label">
							<text>*</text>
							<text>收货地区：</text>
						</view>
						<view class="form-content">
							<input v-model="formData.address_area" placeholder="请输入收货地区" :disabled="!isFormEditable" />
						</view>
					</view>
				</uni-forms-item> -->

		<!-- <uni-forms-item name="address_detail" >
					<view class="form-item" style="border-bottom: none;">
						<view class="form-label">
							<text>*</text>
							<text>详细地址：</text>
						</view>
						<view class="form-content">
							<template v-if="isFormEditable">
								<input v-model="formData.address_detail" placeholder="请输入详细地址" />
							</template>
							<template v-else>
								<text class="disabled-text">{{ formData.address_detail || '暂无详细地址' }}</text>
							</template>
						</view>
					</view>
				</uni-forms-item> -->
		</uni-forms>
	</view>

	<view class="app-divide" style="display:none"></view>

	<view class="app-wrapper">
		<text class="app-title" style="display:none">体检人信息</text>
		<view class="tip-content" style="display:none">
			<text>进入APP首页 → 点击【我的】→ 选择【绑定医保卡】<br /><br />
				将实体医保卡置于光线充足处，对准屏幕扫码框<br />
				📌 提示：若为电子医保卡，可直接点击"同步电子医 保凭证"<br /><br />
				输入医保卡密码（默认密码或已修改的个人密码）<br /><br />
				完成人脸识别验证 → 点击【确认绑定】</text>
		</view>

		<view class="confirm-button" @click="submitForm">
			<text>下一步</text>
		</view>
	</view>
	</view>

	<!-- 选择联系人弹窗 -->
	<view v-if="showCustomerPicker" class="customer-picker-overlay" @click="closeCustomerPicker">
		<view class="customer-picker-content" @click.stop>
			<view class="picker-header">
				<text class="picker-title">选择体检人</text>
				<view class="picker-close" @click="closeCustomerPicker">
					<text>×</text>
				</view>
			</view>

			<scroll-view class="picker-list" scroll-y>
				<view v-for="(customer, index) in customerList" :key="index" class="customer-item"
					@click="selectCustomer(customer)">
					<view class="customer-info">
						<text class="customer-name">{{ customer.name }}</text>
						<text class="customer-phone">{{ customer.phone }}</text>
					</view>
					<view class="customer-arrow">
						<text>></text>
					</view>
				</view>

				<view v-if="customerList.length === 0" class="empty-tip">
					<text>暂无联系人数据</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>
<script setup>
	import {
		ref,
		nextTick
	} from "vue";
	import {
		imgUrl
	} from "../../../utils/global";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		getCustomerListApi
	} from "@/api/customer";
	import {
		getCaseListApi
	} from '@/api/case';
	import {
		useUserStore
	} from "@/store/user";
	import {
		getMyExaminationDetailApi,
		getInstitutionList,
		updataismarried
	} from "@/api/reserve";
	import {
		useOrderStore
	} from '@/store/order';
	import mpHtml from '../../../components/mp-html/components/mp-html/mp-html.vue';
	const formRef = ref(null);
	const userStore = useUserStore();
	const orderStore = useOrderStore();

	const genderType = [{
			label: "女",
			value: 1
		},
		{
			label: "男",
			value: 0
		},
	];

	const licenseType = [{
			label: "身份证",
			value: 0
		},
		{
			label: "护照",
			value: 1
		}
	];
	const marriedType = [{
			label: "已婚",
			value: 1
		},
		{
			label: "未婚",
			value: 0
		}
	];
	const formData = ref({
		name: "",
		phone: "",
		license_type: 0,
		license_number: "",
		gender: 1,
		address_area: "",
		address_detail: "",
		ismarried: "",
		brandid: ""
	});

	// 套餐信息
	const customerList = ref([]);
	const currentCustomer = ref(null);
	const currentCheckUp = ref(null);

	// 控制表单是否可编辑
	const isFormEditable = ref(true);

	// 控制选择联系人弹窗
	const showCustomerPicker = ref(false);

	// 初始化
	onLoad(async (options) => {
		if (typeof options.id === 'undefined') {
			uni.showToast({
				title: '数据载入失败',
				icon: 'none'
			});
			return;
		}
		await nextTick();
		try {
			const results = await getMyExaminationDetailApi({
				id: Number(options.id)
			});
			currentCheckUp.value = results;
			isFormEditable.value = results.type !== 0;
			if (results.type === 0) {
				isMarried.value = results.ismarried
				formData.value.name = results.name;
				formData.value.phone = results.phonenumber;
				formData.value.gender = results.gender;
				formData.value.ismarried = results.ismarried;
				formData.value.license_number = results.certificatenumber;
				formData.value.brandid = results.brandid
				formData.value.packageid = results.packageid
				formData.value.license_type = Number(results.certificatetype) || 0;
				if (results.address) {
					const addressData = JSON.parse(results.address);
					if (Array.isArray(addressData) && addressData.length >= 2) {
						formData.value.address_area = addressData[0] || '';
						formData.value.address_detail = addressData[1] || '';
					}
				}

				// orderStore.setCustomerInfo({
				// 	id: currentCheckUp.value.id,
				// 	planId: currentCheckUp.value.planid,
				// 	name: formData.value.name,
				// 	phone: formData.value.phone,
				// 	license_type: formData.value.license_type,
				// 	license_number: formData.value.license_number,
				// 	brandid: formData.value.brandid,
				// 	gender: formData.value.gender,
				// 	ismarried: formData.value.ismarried,
				// 	address_area: formData.value.address_area,
				// 	address_detail: formData.value.address_detail,
				// });
			}
		} catch (error) {
			console.error('getMyExaminationDetailApi error', error);
			uni.showToast({
				title: '获取套餐详情失败',
				icon: 'none'
			});
		}

		// 载入体检人信息
		try {
			const results = await getCustomerListApi({
				uid: userStore.userInfo.id
			});
			customerList.value = results[0];
		} catch (error) {
			console.error('getCustomerListApi error', error);
			uni.showToast({
				title: '获取体检人列表失败',
				icon: 'none'
			});
		}
	});

	// 处理证件类型变化
	const handleLicenseTypeChange = (e) => {
		formData.value.license_type = parseInt(e.detail.value);
	};

	// 处理性别变化
	const handleGenderChange = (e) => {
		formData.value.gender = parseInt(e.detail.value);
	};

	// 表单校验
	const validateForm = async () => {
		// 手动校验各个字段
		if (!formData.value.name.trim()) {
			uni.showToast({
				title: "姓名不能为空",
				icon: "none",
			});
			return false;
		}

		if (!formData.value.phone.trim()) {
			uni.showToast({
				title: "手机号不能为空",
				icon: "none",
			});
			return false;
		}

		const phonePattern = /^1[3456789]\d{9}$/;
		if (!phonePattern.test(formData.value.phone)) {
			uni.showToast({
				title: "手机号格式不正确",
				icon: "none",
			});
			return false;
		}

		if (!formData.value.license_number.trim()) {
			uni.showToast({
				title: "证件号码不能为空",
				icon: "none",
			});
			return false;
		}

		// if (!formData.value.address_area.trim()) {
		// 	uni.showToast({
		// 		title: "请选择所在地区",
		// 		icon: "none",
		// 	});
		// 	return false;
		// }

		// if (!formData.value.address_detail.trim()) {
		// 	uni.showToast({
		// 		title: "请输入详细地址",
		// 		icon: "none",
		// 	});
		// 	return false;
		// }

		return true;
	};

	// 打开选择联系人弹窗
	const openCustomerPicker = () => {
		if (customerList.value.length === 0) {
			uni.showToast({
				title: "暂无联系人数据",
				icon: "none",
			});
			return;
		}
		showCustomerPicker.value = true;
	};

	// 选择联系人
	const selectCustomer = (customer) => {
		currentCustomer.value = customer;
		// 填充表单数据
		formData.value.name = customer.name || "";
		formData.value.phone = customer.phonenumber || "";
		// 如果有其他字段也可以填充
		if (customer.gender !== undefined) {
			formData.value.gender = customer.gender;
		}
		if (customer.certificatenumber) {
			formData.value.license_number = customer.certificatenumber;
		}
		if (customer.certificatetype !== undefined) {
			formData.value.license_type = Number(customer.certificatetype) || 0;
		}
		if (customer.reportdeliveryaddress) {
			// 解析地址数据 - 支持JSON数组格式
			try {
				const addressData = JSON.parse(customer.reportdeliveryaddress);
				if (Array.isArray(addressData) && addressData.length >= 2) {
					formData.value.address_area = addressData[0] || '';
					formData.value.address_detail = addressData[1] || '';
				}
			} catch (error) {
				// 如果解析失败，尝试按旧格式处理
				const addressParts = customer.reportdeliveryaddress.split(' ');
				formData.value.address_area = addressParts[0] || '';
				formData.value.address_detail = addressParts[1] || '';
			}
		}

		showCustomerPicker.value = false;
		uni.showToast({
			title: "已选择联系人",
			icon: "success",
		});
	};
	const rich = ref(`<div class="tongzhi" style="line-height: 28px;padding: 5px 0; font-size: 16px; color:#043534;">
    <p></p>
    <p></p>
    <p>亲爱的同事：</p>
    <p style="text-indent: 2em;">本年度员工体检时间为2025年7月1日-2025年9月30日，请参加体检的同事尽早扫描二维码预约。</p>
    <p style="text-indent: 2em;">请按如下提示提前预约，并携带本人身份证按时前往体检机构体检。</p>
    <p style="text-indent: 2em;">体检预约前请仔细阅读<a class="btn-xuzhi" href="https://www.shhegao.com/tke2024/xuzhi.html" style="display: inline-block;padding: 4px 6px 2px;border-radius: 3px;background: linear-gradient(41deg,#713075,#ea6830);color: #eee;text-indent: 0;margin-left: 4px;text-decoration: none;box-shadow: 2px 2px 9px 1px #04353409;white-space: nowrap;">
        <i class="icon icon-click" style="display: inline;height: 20px;vertical-align: middle;position: relative; top:-1px;">
            <svg style="display: inline;height: 20px;vertical-align: middle;position: relative; top:-1px;" t="1688540518699" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4895"><path d="M600.459598 264.304094c0 53.626656-20.121285 102.665514-53.211225 139.783324-9.446528 10.602508-23.155734 16.183726-37.370681 15.840545h-2.546769c-6.068897 0-11.090188-5.003228-11.090188-11.090188l-0.072249-19.633605c0-5.003228 1.968779-9.771647 5.50897-13.384086l0.090311-0.090311c29.730372-29.730372 46.148907-69.322703 46.148907-111.443741 0-42.1391-16.418535-81.713368-46.148907-111.534052-29.820683-29.730372-69.394952-46.148907-111.534052-46.148907s-81.713368 16.418535-111.534052 46.148907c-29.730372 29.802621-46.148907 69.394952-46.148907 111.534052s16.418535 81.713368 46.148907 111.534052l0.072249 0.072248c4.027869 4.027869 6.321768 9.518777 6.249519 15.190306-0.090311 24.383963-29.802621 36.2147-46.654649 18.640185-36.142451-37.786111-58.395075-88.938246-58.395075-145.364542 0-116.21216 94.122096-210.334256 210.243946-210.334257s210.243945 94.158221 210.243945 210.28007z m0 0" p-id="4896" fill="#ffffff"></path><path d="M811.859524 550.445381v292.047625s-0.90311 7.549997-9.121408 18.965305c-15.190306 21.186954-39.75489 33.433122-65.782513 33.433122l-304.040922 0.090311c-28.339583 0-55.107756-12.896407-72.75452-34.986471l-166.714057-208.275166c-13.474397-16.833965-16.996525-39.827139-8.380858-59.623305 5.743778-13.221526 16.833965-24.474274 37.623552-24.474274 10.674757 0 23.824035 2.9622 40.152258 10.096767 54.204646 24.311714 73.585381 75.55416 73.585381 75.55416l0.90311-185.444552 0.252871-54.782636 0.650239-134.111795c0.072249-18.477625 8.543418-36.05214 23.246044-47.304888 9.193657-7.062318 20.608964-12.896407 32.927381-12.896407 8.453107 0 17.411956 2.79964 26.370804 9.771647 14.377507 11.252747 22.505495 28.664703 22.577743 46.889457l0.48768 137.399115 0.162559 54.854885 0.16256 39.91745s25.702503-35.076782 63.398303-35.076782c20.211596 0 43.78276 10.024518 68.654402 40.82056 0 0 23.083485-38.76147 60.201295-38.76147 19.471046 0 42.789339 10.602508 68.654401 43.024148 0 0 22.342935-43.692449 52.723547-43.692449 10.259327 0 21.439825 5.003228 33.017691 18.387314 13.655019 16.201789 21.042457 36.901064 21.042457 58.178329z m0 0" p-id="4897" fill="#ffffff"></path></svg>
        </i>
        体检须知
    </a></p>
    <p></p>
</div>`)
	// 关闭选择联系人弹窗
	const closeCustomerPicker = () => {
		showCustomerPicker.value = false;
	};
	const linkTaps = (e) => {
		uni.navigateTo({
			url: "/pages/webview/webview?link=" + e.href
		})
	}

	const changeCalendar = (e) => {
		console.log(e)
	}
	// 判断是不是只能选择一个机构,如果是的话,自动选择,跳转到选择套餐页
	const judgingInstitutions = (e) => {
		return new Promise((resolve, reject) => {
			getInstitutionList().then(list => {
				// 数据数组
				let brandList = []
				// 机构数组
				let institution = []
				if (orderStore.customerInfo.brandid) {
					institution = orderStore.customerInfo.brandid.split(",")
					if (typeof institution == 'string' && institution) {
						institution = [institution]
					}
				}
				// 如果只有用户一个机构的话
				if (institution.length == 1) {
					let info = list.find(item => item.brandid == institution[0])
					orderStore.setBrand(info);
					orderStore.customerInfo.brand_list = institution
					resolve()
				} else {
					reject()
				}
			}).catch(err => {
				reject()
			})
		})

	}
	// 判断是不是只能选择一个套餐,如果是的话,自动选择,跳转到套餐详情页
	const determinePackage = (e) => {
		return new Promise((resolve, reject) => {
			getCaseListApi({
				id: orderStore.customerInfo.id
			}).then(list => {
				let packageList = []
				list.forEach(item => {
					item['status'] = false
					if (item.sex == 0) {
						if (orderStore.customerInfo.gender != 0) {
							item['status'] = true
						}
					} else {
						if (orderStore.customerInfo.gender != item.sex) {
							item['status'] = true
						}
						if (orderStore.customerInfo.ismarried != item.ismarried) {
							item['status'] = true
						}
					}
					if (!item['status']) {
						packageList.push(item)
					}
				});
				if (packageList.length == 1) {
					orderStore.setPackage(packageList[0])
					resolve()
				} else {
					reject()
				}
				// orderStore.setPackage(info);
			}).catch(() => {
				reject()
			})

		})
	}
	const isMarried = ref(0)
	// 已婚未婚状态切换
	const changeMarried = (e) => {
		isMarried.value = e.detail.value
	}
	// 提交表单
	const submitForm = async () => {
		const isValid = await validateForm();
		if (!isValid) return;
		uni.showToast({
			title: '选择联系人中...',
			icon:"none"
		});
		try {
			// 判断当前婚姻状态和数据库的婚姻状态是否一致
			console.log(isMarried.value, formData.value.ismarried)
			if (isMarried.value != formData.value.ismarried) {
				updataismarried({
					id: currentCheckUp.value.id,
					ismarried: isMarried.value
				}).then(() => {
					uni.showToast({
						title:"婚姻状态修改成功",
						icon:"none"
					})
					formData.value.ismarried = isMarried.value
					submitFuntion()
				})
				return
			}
			submitFuntion()
		} catch (error) {
			uni.hideToast();
			console.error("提交失败:", error);
		}
	};
	const submitFuntion = () => {
		// 保存体检人信息到orderStore
		orderStore.setCustomerInfo({
			id: currentCheckUp.value.id,
			planId: currentCheckUp.value.planid,
			name: formData.value.name,
			phone: formData.value.phone,
			license_type: formData.value.license_type,
			license_number: formData.value.license_number,
			brandid: formData.value.brandid,
			gender: formData.value.gender,
			ismarried: formData.value.ismarried,
			address_area: formData.value.address_area,
			address_detail: formData.value.address_detail,
			packageid: formData.value.packageid,
		});
		judgingInstitutions().then(() => {
			determinePackage().then(() => {
				// 去套餐详情页
				uni.navigateTo({
					url: '/pages/case/overview/index'
				});
			}).catch(() => {
				// 去选择套餐页
				uni.redirectTo({
					url: '/pages/case/select/index'
				});
			})
		}).catch(() => {
			// 去选择机构页
			uni.redirectTo({
				url: "/pages/reserve/brand/index"
			})
		})
		return
		// 去选择机构页
		uni.redirectTo({
			url: "/pages/reserve/brand/index"
		})
	}
</script>
<style src="./style.scss" scoped />